1.11 File Handling in C Programming
Module 1.11 • Persistent Storage, I/O Streams, Binary Records & Random Access
1.11.1 Introduction to File Handling
So far, most programs store data in variables and arrays. The problem is:
- Data remains only while the program runs.
- When the program terminates, data is lost.
To store data permanently, C provides File Handling. A file allows data to be:
- Saved permanently
- Retrieved later
- Modified when required
- Shared between programs
Real-Life Examples
- Student Records
- Employee Databases
- Banking Applications
- Inventory Systems
- Hospital Management Systems
1.11.2 What is a File?
A file is a collection of related data stored on secondary storage devices such as:
- Hard Disk
- SSD
- USB Drive
- Memory Card
Example:
Employee Records
1001 Ravi 45000
1002 Meera 52000
1003 Arjun 61000
1.11.3 Advantages of File Handling
Permanent Storage
Data remains even after program termination.
Large Data Storage
Files can store much larger data than variables.
Data Sharing
Multiple programs can access the same file.
Easy Data Management
Records can be added, modified, searched, and deleted.
1.11.4 Types of Files in C
C supports two major file formats:
Text Files
Data is stored as characters.
Example:
Ravi 25
Meera 30
File extension:
.txt
.dat
.csv
Binary Files
Data is stored exactly as it exists in memory.
Example:
1010100010110010
Not human-readable. Common extensions:
.bin
.dat
1.11.5 Text File vs Binary File
| Feature | Text File | Binary File |
|---|---|---|
| Readability | Human readable | Not readable |
| Speed | Slower | Faster |
| Storage | More space | Less space |
| Portability | High | Medium |
| Editing | Text editor | Special programs |
1.11.6 File Processing Steps
Every file operation follows three steps:
Open File
↓
Read / Write
↓
Close File
1.11.7 FILE Pointer
C uses a special pointer called FILE pointer.
Declaration
FILE *fp;
This pointer connects the program and file.
1.11.8 Opening a File
The function used is: fopen()
Syntax
FILE *fp;
fp = fopen("employees.txt","r");
1.11.9 fopen() Syntax
fopen(filename, mode);
Example:
FILE *fp;
fp = fopen("sales.txt","w");
1.11.10 File Opening Modes
| Mode | Description |
|---|---|
| r | Read |
| w | Write |
| a | Append |
| r+ | Read + Write |
| w+ | Write + Read |
| a+ | Append + Read |
1.11.11 Read Mode
fp = fopen("records.txt","r");
Requirements:
- File must already exist.
Purpose:
- Read data only.
1.11.12 Write Mode
fp = fopen("records.txt","w");
Purpose:
- Create file
- Write data
Important: Existing contents are erased.
1.11.13 Append Mode
fp = fopen("records.txt","a");
Purpose:
- Add data at end of file.
Existing data remains unchanged.
1.11.14 Checking File Open Errors
Always verify whether file opened successfully.
Example
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("report.txt","r");
if(fp == NULL)
{
printf("File cannot be opened");
return 1;
}
fclose(fp);
return 0;
}
1.11.15 Closing a File
Use: fclose()
Syntax
fclose(fp);
Benefits:
- Saves pending data
- Releases memory
- Prevents file corruption
1.11.16 Writing Characters to a File
Function: fputc()
Example
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("letters.txt","w");
fputc('X',fp);
fputc('Y',fp);
fputc('Z',fp);
fclose(fp);
return 0;
}
File Content:
XYZ
1.11.17 Reading Characters from a File
Function: fgetc()
Example
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("letters.txt","r");
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output:
XYZ
1.11.18 Character Copy Program
#include<stdio.h>
int main()
{
FILE *src,*dest;
char ch;
src=fopen("input.txt","r");
dest=fopen("output.txt","w");
while((ch=fgetc(src))!=EOF)
{
fputc(ch,dest);
}
fclose(src);
fclose(dest);
return 0;
}
1.11.19 Writing Strings
Function: fputs()
Example
FILE *fp;
fp=fopen("message.txt","w");
fputs("Welcome to Coding Hub",fp);
fclose(fp);
1.11.20 Reading Strings
Function: fgets()
Example
char text[100];
fgets(text,100,fp);
1.11.21 String File Example
#include<stdio.h>
int main()
{
FILE *fp;
char line[100];
fp=fopen("message.txt","r");
fgets(line,100,fp);
printf("%s",line);
fclose(fp);
return 0;
}
Output:
Welcome to Coding Hub
1.11.22 Formatted File Output
Function: fprintf(). Works like printf().
Example
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("staff.txt","w");
fprintf(fp,
"ID=%d Salary=%.2f",
501,
48500.75);
fclose(fp);
return 0;
}
1.11.23 Formatted File Input
Function: fscanf(). Works like scanf().
Example
int id;
float salary;
fscanf(fp, "%d %f", &id, &salary);
1.11.24 Employee Record Example
#include<stdio.h>
int main()
{
FILE *fp;
char name[20];
int age;
fp=fopen("employee.txt","w");
fprintf(fp, "Karan %d", 29);
fclose(fp);
fp=fopen("employee.txt","r");
fscanf(fp, "%s%d", name, &age);
printf("%s %d", name, age);
fclose(fp);
return 0;
}
Output:
Karan 29
1.11.25 Writing Structures to File
Consider:
struct Product
{
int id;
float price;
};
Write structure:
fwrite(&item, sizeof(item), 1, fp);
1.11.26 Reading Structures from File
fread(&item, sizeof(item), 1, fp);
1.11.27 Binary File Example
#include<stdio.h>
struct Product
{
int id;
float price;
};
int main()
{
FILE *fp;
struct Product p =
{
101,
899.50
};
fp=fopen("products.dat","wb");
fwrite(&p, sizeof(p), 1, fp);
fclose(fp);
return 0;
}
1.11.28 Reading Binary Records
#include<stdio.h>
struct Product
{
int id;
float price;
};
int main()
{
FILE *fp;
struct Product p;
fp=fopen("products.dat","rb");
fread(&p, sizeof(p), 1, fp);
printf("%d %.2f", p.id, p.price);
fclose(fp);
return 0;
}
Output:
101 899.50
1.11.29 Random File Access
Normally files are accessed sequentially. Random access allows direct movement to any location.
Functions used:
- fseek()
- ftell()
- rewind()
1.11.30 fseek()
Moves file pointer.
Syntax
fseek(fp, offset, position);
1.11.31 Example of fseek()
fseek(fp, 20, SEEK_SET);
Meaning: Move 20 bytes from beginning.
1.11.32 ftell()
Returns current position.
Example
long pos;
pos = ftell(fp);
printf("%ld",pos);
1.11.33 rewind()
Moves pointer to beginning.
Example
rewind(fp);
Equivalent to:
fseek(fp,0,SEEK_SET);
1.11.34 File Position Example
FILE *fp;
fp=fopen("data.txt","r");
printf("%ld\n",ftell(fp));
fseek(fp,15,SEEK_SET);
printf("%ld\n",ftell(fp));
rewind(fp);
printf("%ld\n",ftell(fp));
Output:
0
15
0
1.11.35 End of File Detection
EOF means: End Of File. Used while reading files.
Example
while((ch=fgetc(fp))!=EOF)
{
printf("%c",ch);
}
1.11.36 feof()
Checks whether end of file reached.
Example
if(feof(fp))
{
printf("End of File");
}
1.11.37 ferror()
Checks file errors.
Example
if(ferror(fp))
{
printf("File Error");
}
1.11.38 clearerr()
Clears file error indicators.
Example
clearerr(fp);
1.11.39 fflush()
Forces buffered data to be written immediately.
Example
fflush(fp);
1.11.40 rename()
Renames files.
Example
rename("oldreport.txt", "newreport.txt");
1.11.41 remove()
Deletes a file.
Example
remove("oldreport.txt");
1.11.42 Temporary Files
Function: tmpfile()
Creates temporary file automatically deleted after program termination.
1.11.43 Command Line Arguments
main() can receive arguments from command prompt.
Syntax
int main(int argc, char *argv[])
1.11.44 Example
Command:
app.exe India Chennai 2026
Values:
argc = 4
argv[0] = app.exe
argv[1] = India
argv[2] = Chennai
argv[3] = 2026
Applications of File Handling
- Banking Systems
- Payroll Management
- Student Information Systems
- E-Commerce Applications
- Medical Records
- Inventory Control
- Library Management
Summary
- Files provide permanent storage.
- fopen() opens a file.
- fclose() closes a file.
- fgetc() and fputc() handle characters.
- fgets() and fputs() handle strings.
- fscanf() and fprintf() perform formatted I/O.
- fread() and fwrite() process binary data.
- fseek(), ftell(), and rewind() enable random access.
- feof() and ferror() help detect file conditions.
- File handling is essential for real-world software development.
Click your choice for each question to view feedback immediately. Complete all questions to evaluate your metric score.